/**
 * @author Eduardo Leonne Souza de Oliveira
 * @version 1.0
 * Date: 2011-12-29
 * Last change: 2011-12-29 
 * 
 */

package com.leonne.harpacristabrasileira.singleton;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.leonne.harpacristabrasileira.tools.MyConstants;
import com.leonne.harpacristabrasileira.tools.ReadFile;

/**
 * Singleton that provides connection to the database
 */

public class Connection extends SQLiteOpenHelper {

	private static Connection conn;
	private static SQLiteDatabase mDataBase;
	private static Context context;

	/**
	 * Constructor that prevents a creation of a direct instance of this class
	 * 
	 * @param context Base context of the application.  
	 */
	private Connection(Context context) {
		super(context, MyConstants.DATABASE_NAME, null, MyConstants.DATABASE_VERSION);
	}

	/**
	 * Returns a writable pointer to the database
	 * 
	 * @return A read/write database object
	 */
	public static SQLiteDatabase getConnection(Context c) {
		context = c;		
		File dir = new File(MyConstants.DATABASE_PATH);
		if (!dir.exists())
			dir.mkdir();
		File databaseFile = new File(MyConstants.DATABASE_PATH + MyConstants.DATABASE_NAME);
		if (!databaseFile.exists())
			Connection.copyDatabase();
		// Verify if the singleton instance is already created
		if (Connection.conn == null)
			Connection.conn = new Connection(context);
		// Verify if the internal reference to the writable database is already filled
		if (Connection.mDataBase == null)
			Connection.mDataBase = Connection.conn.getWritableDatabase();
		return Connection.mDataBase;
	}
	
	/**
	 * (non-Javadoc)
	 * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		// Verify if the internal reference to the writable database is already filled
		if (Connection.mDataBase == null)
			Connection.mDataBase = db;
	}
	
	/**
	 * Copy the database file in assets folder to the databases folder in the device
	 * 
	 * @return True if the file was copied with success, otherwise false
	 */
	
	private static boolean copyDatabase() {
		try {
			String outfilename = MyConstants.DATABASE_PATH + MyConstants.DATABASE_NAME;
			
			// Open your local db as the input stream
			InputStream myinput = context.getAssets().open(MyConstants.DATABASE_NAME);

			// Path to the just created empty db

			// Open the empty db as the output stream
			OutputStream myoutput = new FileOutputStream(outfilename);

			// transfer byte to inputfile to outputfile
			byte[] buffer = new byte[1024];
			int length;
			while ((length = myinput.read(buffer)) > 0)
				myoutput.write(buffer, 0, length);

			// Close the streams
			myoutput.flush();
			myoutput.close();
			myinput.close();
			return true;
		} catch(Exception e) {
			e.getMessage();
			return false;
		}

	}

	
	/**
	 * (non-Javadoc)
	 * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.e("Harpa", "Substituindo dados antigos");
		ReadFile rf = new ReadFile(Connection.context, MyConstants.UPDATESCRIPT);
		String fullSql = rf.getString();
		String[] statements = fullSql.split("\\|");
		// Unfortunately SQLite doesn't have support to execute multiple statements. It's needed to execute one per one
		for (String sql : statements){
			try{
				db.execSQL(sql);
			}catch (Exception e){
				e.getMessage();
			}
		}		
	}
	
}
